package org.hecf.demo.user.controller;

import com.alibaba.fastjson.JSONObject;
import org.hecf.demo.user.entity.User;
import org.hecf.demo.user.service.IUserService;
import org.hecf.demo.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping(value = "/base/user")
public class UserController {
    @Autowired
    private IUserService userService;

    private String baseUrl = null;

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(){
        return getDefaultViewName("edit");
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public String add(@RequestBody User user){
        JSONObject jsonObject = new JSONObject();
        try {
            this.userService.insert(user,jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping(value = "/addBatch",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject addBatch(@RequestBody List<UserVO> userVOS){
        List<User> users = new ArrayList<>(userVOS.size());
        for (int i=0;i<userVOS.size();i++){
            UserVO userVO = userVOS.get(i);
            User user = new User();
            user.setId(i+1);
            user.setName(userVO.getName());
            user.setAddress(userVO.getAddress());
//            user.setBirthday(userVO.getBirthday());
            users.add(user);
        }
        JSONObject result = userService.insert(users);
        return result;
    }

    private String getDefaultViewName(String name){
        if(name.startsWith("/")){
            return baseUrl+name;
        }else{
            return baseUrl+"/"+name;
        }

    }

    @RequestMapping(value = "/test")
    @ResponseBody
    public String test(){
        return "hello";
    }

    /** 初始化init的方法 */
    @PostConstruct
    public void init() {
        RequestMapping requestMapping = (RequestMapping)AnnotationUtils.findAnnotation(this.getClass(), RequestMapping.class);
        if(!Objects.isNull(requestMapping)){
            baseUrl = requestMapping.value()[0];
            if(!baseUrl.startsWith("/")){
                baseUrl = "/"+baseUrl;
            }
        }
    }

}
